// 1. React核心库
import React, { useState, useEffect, useCallback } from 'react';

// 2. UI组件库 - 按字母顺序排列
import {
  Card,
  Row,
  Col,
  Button,
  Tag,
  Space,
  Descriptions,
  message,
  Spin,
  Form,
  Input,
  Switch,
  Modal,
} from 'antd';

// 3. 图标库
import {
  UserOutlined,
  EditOutlined,
  SaveOutlined,
  CloseOutlined,
  ArrowLeftOutlined,
  LockOutlined,
} from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProForm, ProFormText, ProFormSwitch } from '@ant-design/pro-components';

// 5. 工具库
import { history, useParams, useSearchParams } from '@umijs/max';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 生成的类型定义 (必须使用，禁止手工定义)
import type { UserProfile } from '@/services/generated/src';



const UserDetail: React.FC = () => {
  const params = useParams();
  const [searchParams] = useSearchParams();
  const [form] = Form.useForm();
  const [isEditing, setIsEditing] = useState(searchParams.get('mode') === 'edit');
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [userDetail, setUserDetail] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(false);
  const [updateLoading, setUpdateLoading] = useState(false);
  const [resetPasswordLoading, setResetPasswordLoading] = useState(false);

  const userId = params.id as string;

  // 获取用户详情
  const fetchUserDetail = useCallback(async () => {
    try {
      setLoading(true);
      await autoLoginInDev();

      const response = await apiClients.users.usersRetrieve({ id: Number(userId) });
      console.log('🚀 用户详情API响应:', response);

      // 🔑 关键：手动提取data字段（不使用useRequest，无自动dataField处理）
      const responseData = (response as any).data || response;
      setUserDetail(responseData);
    } catch (error) {
      message.error('获取用户详情失败');
    } finally {
      setLoading(false);
    }
  }, [userId]);

  // 更新用户信息
  const handleUpdate = async (values: any) => {
    try {
      setUpdateLoading(true);
      const response = await apiClients.users.usersPartialUpdate({
        id: Number(userId),
        patchedUserUpdateRequest: values
      });

      console.log('🚀 更新API响应:', response);

      // 🔑 关键：手动提取data字段（不使用useRequest，无自动dataField处理）
      const responseData = (response as any).data || response;
      message.success('更新成功');
      setIsEditing(false);
      fetchUserDetail(); // 重新获取用户详情
      return responseData;
    } catch (error) {
      message.error('更新失败');
      throw error;
    } finally {
      setUpdateLoading(false);
    }
  };

  // 重置密码
  const handleResetPassword = async (values: { new_password: string }) => {
    try {
      setResetPasswordLoading(true);
      await apiClients.users.usersResetPasswordCreate({
        id: Number(userId),
        userPasswordResetRequest: values
      });
      message.success('密码重置成功');
      setPasswordModalVisible(false);
    } catch (error) {
      message.error('密码重置失败');
    } finally {
      setResetPasswordLoading(false);
    }
  };

  // 初始化数据获取
  useEffect(() => {
    fetchUserDetail();
  }, [fetchUserDetail]);

  // 设置表单初始值
  useEffect(() => {
    if (userDetail) {
      form.setFieldsValue({
        email: userDetail.email,
        first_name: userDetail.first_name,
        last_name: userDetail.last_name,
        is_active: userDetail.is_active,
        is_staff: userDetail.is_staff,
      });
    }
  }, [userDetail, form]);

  if (loading) {
    return (
      <PageContainer>
        <Card>
          <Spin size="large" style={{ display: 'block', textAlign: 'center', padding: '50px' }} />
        </Card>
      </PageContainer>
    );
  }

  if (!userDetail) {
    return (
      <PageContainer>
        <Card>
          <div style={{ textAlign: 'center', padding: '50px' }}>
            用户不存在
          </div>
        </Card>
      </PageContainer>
    );
  }



  return (
    <PageContainer
      header={{
        title: `用户详情 - ${userDetail.username}`,
        breadcrumb: {
          items: [
            { title: '首页' },
            { title: '用户管理' },
            { title: '用户列表', path: '/users/list' },
            { title: '用户详情' },
          ],
        },
        extra: [
          <Button
            key="back"
            icon={<ArrowLeftOutlined />}
            onClick={() => history.back()}
          >
            返回
          </Button>,
          !isEditing && (
            <Button
              key="edit"
              type="primary"
              icon={<EditOutlined />}
              onClick={() => setIsEditing(true)}
            >
              编辑
            </Button>
          ),
          !isEditing && (
            <Button
              key="resetPassword"
              icon={<LockOutlined />}
              onClick={() => setPasswordModalVisible(true)}
            >
              重置密码
            </Button>
          ),
        ].filter(Boolean),
      }}
    >
      <Row gutter={24}>
        <Col span={24}>
          <Card title="基本信息">
            {isEditing ? (
              <ProForm
                form={form}
                onFinish={async (values) => {
                  await handleUpdate(values);
                }}
                submitter={{
                  render: (props) => (
                    <Space>
                      <Button
                        type="primary"
                        loading={updateLoading}
                        onClick={() => props.form?.submit?.()}
                        icon={<SaveOutlined />}
                      >
                        保存
                      </Button>
                      <Button
                        onClick={() => {
                          setIsEditing(false);
                          form.resetFields();
                        }}
                        icon={<CloseOutlined />}
                      >
                        取消
                      </Button>
                    </Space>
                  ),
                }}
              >
                <Row gutter={16}>
                  <Col span={12}>
                    <ProFormText
                      name="email"
                      label="邮箱"
                      rules={[
                        { required: true, message: '请输入邮箱' },
                        { type: 'email', message: '请输入有效的邮箱地址' },
                      ]}
                    />
                  </Col>
                  <Col span={12}>
                    <ProFormText
                      name="first_name"
                      label="名字"
                      rules={[{ required: true, message: '请输入名字' }]}
                    />
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col span={12}>
                    <ProFormText
                      name="last_name"
                      label="姓氏"
                      rules={[{ required: true, message: '请输入姓氏' }]}
                    />
                  </Col>
                  <Col span={12}>
                    <ProFormSwitch
                      name="is_active"
                      label="是否激活"
                    />
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col span={12}>
                    <ProFormSwitch
                      name="is_staff"
                      label="管理员权限"
                    />
                  </Col>
                </Row>
              </ProForm>
            ) : (
              <Descriptions column={2} bordered>
                <Descriptions.Item label="用户ID">{userDetail.id}</Descriptions.Item>
                <Descriptions.Item label="用户名">{userDetail.username}</Descriptions.Item>
                <Descriptions.Item label="邮箱">{userDetail.email}</Descriptions.Item>
                <Descriptions.Item label="姓名">{userDetail.full_name}</Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={userDetail.is_superuser ? 'red' : userDetail.is_staff ? 'orange' : 'blue'}>
                    {userDetail.is_superuser ? '超级管理员' : userDetail.is_staff ? '管理员' : '普通用户'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="是否激活">
                  <Tag color={userDetail.is_active ? 'success' : 'error'}>
                    {userDetail.is_active ? '激活' : '禁用'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="管理员权限">
                  <Tag color={userDetail.is_staff ? 'warning' : 'default'}>
                    {userDetail.is_staff ? '是' : '否'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="超级管理员">
                  <Tag color={userDetail.is_superuser ? 'error' : 'default'}>
                    {userDetail.is_superuser ? '是' : '否'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="注册时间">
                  {new Date(userDetail.date_joined).toLocaleString()}
                </Descriptions.Item>
                <Descriptions.Item label="最后登录">
                  {userDetail.last_login 
                    ? new Date(userDetail.last_login).toLocaleString() 
                    : '从未登录'
                  }
                </Descriptions.Item>
                {userDetail.groups?.length > 0 && (
                  <Descriptions.Item label="用户组" span={2}>
                    {userDetail.groups.map(group => (
                      <Tag key={group}>{group}</Tag>
                    ))}
                  </Descriptions.Item>
                )}
              </Descriptions>
            )}
          </Card>
        </Col>
      </Row>

      {/* 重置密码模态框 */}
      <Modal
        title="重置密码"
        open={passwordModalVisible}
        onCancel={() => setPasswordModalVisible(false)}
        footer={null}
      >
        <Form
          onFinish={handleResetPassword}
          layout="vertical"
        >
          <Form.Item
            name="new_password"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 8, message: '密码长度至少8位' },
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                loading={resetPasswordLoading}
              >
                确认重置
              </Button>
              <Button onClick={() => setPasswordModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default UserDetail;
